package com.lancoo.answer.view.fragment.readMatch

import android.os.Bundle
import android.os.Handler
import android.view.View
import androidx.databinding.ObservableArrayList
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.lancoo.answer.R
import com.lancoo.answer.databinding.EvViewChildAskBinding
import com.lancoo.answer.databinding.EvViewItemOption2Binding
import com.lancoo.answer.databinding.EvViewReadMatchBinding
import com.lancoo.answer.helper.recyclerview.BindingViewAdapter
import com.lancoo.answer.helper.recyclerview.BindingViewHolder
import com.lancoo.answer.helper.recyclerview.SingleTypeAdapter
import com.lancoo.answer.model.AnswerConstant
import com.lancoo.answer.model.ConstantBean
import com.lancoo.answer.model.bean.Child
import com.lancoo.answer.model.bean.ChildOption
import com.lancoo.answer.model.bean.EvOptionBean
import com.lancoo.answer.model.bean.Ques
import com.lancoo.answer.model.eventBean.CompleteCurrentAnsPointEventBean
import com.lancoo.answer.util.ExamFontSizeAdjustUtils
import com.lancoo.answer.util.paperUtils.FragmentCommunicationUtils
import com.lancoo.answer.view.base.BaseVMFragment
import com.lancoo.answer.view.fragment.option.adapter.ItemPresenter
import com.lancoo.answer.widget.combinationView.ReadingMatchQueseBodyView
import org.greenrobot.eventbus.EventBus

/**
 * Created by Dadong on 2021/12/13
 * Describe: 阅读匹配作答控件
 */

class ReadMatchChildFragment : BaseVMFragment<EvViewReadMatchBinding>(),
    BindingViewAdapter.ItemDecorator {

    private var typeIndex = 0
    private var quesIndex = 0
    private var defaultLoadIndex = 0

    private var optionList = ObservableArrayList<EvOptionBean>()
    private var childList = ObservableArrayList<Child>()
    private lateinit var mAdapter: SingleTypeAdapter<EvOptionBean>
    private lateinit var mAnswerAdapter: SingleTypeAdapter<Child>
    private var callback: OptionCallback? = null
    private lateinit var ques: Ques
    private var currentIndex = 0
    private var isQuick = true

    override fun initView(view: View) {
        if (ConstantBean.constantExamBean == null) {
            return
        }
        val kindBeanList = ConstantBean.constantExamBean!!.TypeList
        typeIndex = requireArguments().getInt(AnswerConstant.KEY_TYPEINDEX)
        quesIndex = requireArguments().getInt(AnswerConstant.KEY_QUESINDEX)
        defaultLoadIndex = requireArguments().getInt(AnswerConstant.KEY_LOADCHILDINDEX)
        ques = kindBeanList!![typeIndex].QuesList!![quesIndex]
        setOptionList(ques.ChildList!![0].ChildOptionList!!)
        childList.addAll(ques.ChildList as ArrayList<Child>)
        mBinding.childStatisticsView.setQues(ques)
        initAdapter()
        initVp()
        updateCheck()
    }

    override fun getLayoutId(): Int {
        return R.layout.ev_view_read_match
    }

    companion object {
        fun loadFragment(typeIndex: Int, quesIndex: Int, defaultLoadIndex: Int): Fragment? {
            val mBundle = Bundle()
            mBundle.putInt(AnswerConstant.KEY_TYPEINDEX, typeIndex)
            mBundle.putInt(AnswerConstant.KEY_QUESINDEX, quesIndex)
            mBundle.putInt(AnswerConstant.KEY_LOADCHILDINDEX, defaultLoadIndex)
            val readMatchChildFragment = ReadMatchChildFragment()
            readMatchChildFragment.arguments = mBundle
            return readMatchChildFragment
        }
    }

    //选项的adapter
    private fun initAdapter() {
        mAdapter = SingleTypeAdapter(requireContext(), R.layout.ev_view_item_option2, optionList)
        mBinding.optionRv.adapter = mAdapter.apply {
            itemPresenter = this@ReadMatchChildFragment.itemPresenter
            itemDecorator = this@ReadMatchChildFragment
        }
        val gridLayoutManger = GridLayoutManager(context, 7)
        mBinding.optionRv.layoutManager = gridLayoutManger

    }

    //小题题干的adapter
    private fun initVp() {
        mAnswerAdapter =
            SingleTypeAdapter(requireContext(), R.layout.ev_view_child_ask, childList)
        mBinding.vpChildAsk.adapter = mAnswerAdapter.apply {
            itemDecorator = object : BindingViewAdapter.ItemDecorator {
                override fun decorator(
                    holder: BindingViewHolder<ViewDataBinding>?,
                    position: Int,
                    viewType: Int
                ) {
                    val itemBinding: EvViewChildAskBinding =
                        holder!!.binding as EvViewChildAskBinding
                    itemBinding.tvChildAsk.setTrainType(0)
                    itemBinding.tvChildAsk.initData(childList[position])
                    itemBinding.tvChildAsk.adjustFontSize()
                }
            }
        }

        mBinding.vpChildAsk.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                mBinding.childStatisticsView.updateChildIndex(position)
                currentIndex = position
                EventBus.getDefault().post(position)
                FragmentCommunicationUtils.switchTestQuesionToEvent(
                    typeIndex,
                    quesIndex,
                    position,
                    false,
                    1
                )
            }
        })
        if (defaultLoadIndex != -1 && defaultLoadIndex < ques.ChildList!!.size) {
            mBinding.vpChildAsk.postDelayed(Runnable {
                mBinding.vpChildAsk.currentItem = defaultLoadIndex
            }, 200)
        }
    }

    private fun updateCheck() {
        resetState()
        childList.forEach { child ->
            optionList.forEach { evOptionBean ->
                if (child.ItemList!![0].StuAnswer == evOptionBean.OptionIndex) {
                    evOptionBean.SelectState = 2
                }
            }
        }
        mAdapter.notifyDataSetChanged()
        mAnswerAdapter.notifyDataSetChanged()
    }

    fun setOptionList(optionList: ArrayList<ChildOption>) {
        this.optionList.clear()
        optionList.forEach {
            val option = EvOptionBean().apply {
                Option = it.Option
                OptionIndex = it.OptionIndex
            }
            this.optionList.add(option)
        }
    }

    fun resetState() {
        optionList.forEach { it.SelectState = 0 }
    }

    override fun decorator(
        holder: BindingViewHolder<ViewDataBinding>?,
        position: Int,
        viewType: Int
    ) {
        val itemBinding: EvViewItemOption2Binding = holder!!.binding as EvViewItemOption2Binding
        when (itemBinding.item!!.SelectState) {
            0 -> {
                itemBinding.btnOption1.setBackgroundResource(R.mipmap.ev_icon_choice_white)
                itemBinding.btnOption1.setTextColor(requireContext().resources.getColor(R.color.c333333))
            }
            1 -> {
                itemBinding.btnOption1.setBackgroundResource(R.mipmap.ev_icon_choice_blue)
                itemBinding.btnOption1.setTextColor(requireContext().resources.getColor(R.color.cffffff))
            }
            2 -> {
                itemBinding.btnOption1.setBackgroundResource(R.mipmap.ev_icon_choice_light_blue)
                itemBinding.btnOption1.setTextColor(requireContext().resources.getColor(R.color.cffffff))
            }
        }
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(itemBinding.btnOption1, 15)
    }

    var itemPresenter = object : ItemPresenter {
        override fun onItemClick(v: View, item: EvOptionBean) {
            if (isQuick) {
                item.SelectState = 1
                mAdapter.notifyDataSetChanged()
                Handler().postDelayed({
                    item.SelectState = 2
                    mAdapter.notifyDataSetChanged()
                    //回显赋值
                    childList[currentIndex].ItemList!![0].StuAnswer = item.OptionIndex
                    updateCheck()
                    //vP 切换到下一个
                    Handler().postDelayed({
                        getNextChildAsk()
                        mBinding.vpChildAsk.setCurrentItem(currentIndex, true)
                        isQuick = true
                        EventBus.getDefault().post(CompleteCurrentAnsPointEventBean())
                    }, 400)
                }, 200)
            }
            isQuick = false
        }
    }

    private fun getNextChildAsk() {
        currentIndex += 1
        if (currentIndex >= childList.size) {
            currentIndex = childList.size - 1
            //切换下一个大题
            FragmentCommunicationUtils.autoNextQuesFragment(this, false)
        }
    }

    fun setCallback(callback: OptionCallback) {
        this.callback = callback
    }

    interface OptionCallback {
        fun clickCallback(item: EvOptionBean)
    }

    fun setCurrentItem(itemIndex: Int) {
        mBinding.vpChildAsk.currentItem = itemIndex
    }

    fun adjustFontSize() {
        mAdapter.notifyDataSetChanged()
        mAnswerAdapter.notifyDataSetChanged()
    }

    fun markQuestion() {
        if (mBinding.vpChildAsk != null)
            mBinding.vpChildAsk.registerOnPageChangeCallback(object : OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    mBinding.vpChildAsk.getChildAt(position)
                        .findViewById<ReadingMatchQueseBodyView>(R.id.tv_child_ask).markQues()
                }
            })
    }

}